﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using System.Data.SqlClient;

namespace www.serviciipeweb.ro.CDC
{
    public static class TableHelper
    {
        public static bool IsCDCEnabled(this Table t)
        {
            if(! t.Parent.IsCDCEnabled())
                return false;

            Server s = t.Parent.Parent;

            string sql = @"
                select is_tracked_by_cdc from " + t.Parent.Name + @".sys.tables
                where [name] = " + SqlUtilities<string>.FormatSQL(t.Name);
            object o = SQLHelperLSN.ExecuteScalar(sql);
            //TODO :o == nulll => table deleted
            
            return bool.Parse(o.ToString());
        }
        public static Index PrimaryKey(this Table t)
        {
            return t.Indexes.Cast<Index>().SingleOrDefault<Index>
                            (
                            (i) => (i.IndexKeyType == IndexKeyType.DriPrimaryKey)
                            );
            
        }
        public static bool HasPrimaryKey(this Table t)
        {
            Index pk = t.PrimaryKey();
            return pk != null && pk.IndexedColumns.Count == 1 && t.Columns[pk.IndexedColumns[0].Name].Identity;
        }
        public static bool HasPrimaryKeyIdentity(this Table t)
        {
            Index pk = t.PrimaryKey();
            return pk != null && pk.IndexedColumns.Count == 1 && t.Columns[pk.IndexedColumns[0].Name].Identity;
        }
        static Dictionary<string, TableCDC> dict;

        public static string FullNameTable(this Table t)
        {
            return t.Parent.Parent.Name + "." + t.Parent.Name + "." + t.Schema + "." + t.Name;
        }
        public static TableCDC TableCDC(this Table t)
        {
            //TODO : threading enable

            if (dict == null)
                dict = new Dictionary<string, TableCDC>();

            string name = t.FullNameTable();
            
            if (!dict.ContainsKey(name))
                dict.Add(name, new TableCDC(t));

            return dict[name];
        }
        public static void ModifyCDC(this Table t, bool Modif)
        {
            
            if (t.IsCDCEnabled() == Modif)
                return;

            //TODO : error
            if (Modif && (!t.Parent.IsCDCEnabled()))
            {
                t.Parent.ModifyCDC(Modif);
            }
            
            t.TableCDC().CDCEnabled = Modif;

        }
        public static bool EnableCDCRecursive(this Table t)
        {
            if (!t.Parent.Parent.IsCDCEnabled())
            {
                if (!t.Parent.Parent.EnableCDC())
                    return false;
            }
            t.Parent.ModifyCDC(true);
            t.ModifyCDC(true);
            return true;
        }
    }
}
